<?php
set_time_limit(0);

include_once('lib/config.php');
include_once('lib/Db.class.php');
include_once('lib/Model.class.php');
include_once('lib/Upyun.class.php');
include_once('lib/Image.class.php');
include_once('lib/Http.class.php');
include_once('lib/Cut.class.php');
include_once('lib/function.php');

$redis = new Redis();
$redis->connect(REDIS_IP,"6379");  //php客户端设置的ip及端口
if(!$redis) die('redis connect fail');

$model = new Model;
$http  = new Http;
$cut   = new Cut;

$pid = getmypid();
$redis->hSet(MH_PIDS, $pid, date('Y-m-d H:i:s').'||mh_zcopy_news');

$limit = 50;
while($limit--) {
  $stop = $redis->get('LNPAN_MH_QUEUE_STOP');
  if($stop) {
    die('stop');
  }

  $rand  = rand(0,10);
  $limit = "0, 10";
  $list = $model->query("select * from news_zcopy where news_state=1 and state in(0,1) limit $limit");
  
  if(empty($list)) {
    sleep(1);
  }

  foreach ($list as $item) {
    $log = date('Y-m-d H:i').'||'.$item['title'].':'.$item['link'];
    $old = $model->find('news', "id='$item[id]'");
    if(empty($old)) {
      $new_data = array(
        'id' => $item['id'],
        'title' => $item['title'],
        'pinyin' => empty($item['pinyin']) ? getMD5($item['title']) : $item['pinyin'],
        'author' => $item['author'],
        'status' => $item['status'],
        'type' => $item['type'],
        'area' => empty($item['area']) ? '大陆' : $item['area'],
        'link' => $item['link'],
        'thumb' => $item['thumb'],
        'thumb2' => $item['thumb2'],
        'info' => strip_tags($item['info']),
        'chapter_count' => $item['chapter_count'],
        'chapter_update' => $item['chapter_update'],
        'chapter' => $item['chapter'],
        'state' => 0,
        'addtime' => time(),
        'uptime' => time(),
      );

      $ret = $model->add('news', $new_data);
      if($ret) {
        $copy_data = array('news_state'=>2);
        $model->save('news_zcopy', "id='$item[id]'", $copy_data);
      } else {
        $log = $model->error();
      }
    }
    else {
      $update_data = array(
        'status' => $item['status'],
        'thumb2' => $item['thumb2'],
        'info' => strip_tags($item['info']),
        'chapter_count' => $item['chapter_count'],
        'chapter_update' => $item['chapter_update'],
        'chapter' => $item['chapter'],
        'state' => 0,
        'uptime' => time(),
      );
      $ret = $model->save('news', "id='$old[id]'", $update_data);
      if($ret) {
        $copy_data = array('news_state'=>2);
        $model->save('news_zcopy', "id='$item[id]'", $copy_data);
      } else {
        $log = $model->error();
      }
    }

    $redis->lPush('New_publish', $item['id'].'||'.$log);
    //print_r($item);
  }

  usleep(1000*100);
}

$model->close();
$redis->hDel(MH_PIDS, $pid);